package com.ld.admin.service.user;

import java.util.Date;

import org.springframework.stereotype.Service;

import com.ld.admin.model.system.SysUserTempModel;
import com.ld.admin.model.system.SystemUser;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.reflect.ClassUtil;
import com.ld.shieldsb.common.core.util.DateUtil;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.StaticParams;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.dao.model.PageNavigationBean;
import com.ld.shieldsb.dao.model.QueryModel;

/**
 * 
 * 临时账号服务类，@Service注解用于自动注入
 * 
 * @ClassName SysUserTempService
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年09月30日 17:06:01
 *
 */
@Service
public class SysUserTempService extends UserCommonService {

    // 用于子类覆盖，扩展doSearch方法中QueryModel的处理（标准queryModel处理完，查询进行前的处理）
    @Override
    protected QueryModel extendDealQuery(QueryModel queryModel) {
        queryModel.addEq(SysUserTempModel::getParentId, Web.Util.getSessionUserId(request)); // 查询自己的下级用户
        return super.extendDealQuery(queryModel);
    }

    // 用于子类覆盖，扩展doSearch方法中PageNavigationBean的处理（查询完成后进行）
    @Override
    protected <T> PageNavigationBean<T> extendDealPageNavigationBean(PageNavigationBean<T> pageNavigationBean) {
        return super.extendDealPageNavigationBean(pageNavigationBean);
    }

    // 删除/停用启用方法子类扩展（删除完成后进行）
    @Override
    protected <T> boolean extendRemove(Boolean flag, Class<T> classOfT, String key, Object value, Integer status, Long userId) {
        if (flag) {
            SystemUser user = (SystemUser) Web.Util.getSessionUser(request);
            String operateName = "";
            String type = TEMP_USER_LOG_OTHER;
            if (status == StaticParams.STATE_DISABLE) {
                operateName = "停用";
                type = TEMP_USER_LOG_DISABLE;
            } else if (status == StaticParams.STATE_NORMAL) {
                operateName = "启用";
                type = TEMP_USER_LOG_ENABLE;
            }
            recordTempUserLog(user, ClassUtil.obj2long(value), type, operateName);
        }
        return flag;
    }

    // AddOrUpdate扩展（AddOrUpdate方法完成后进行）
    @Override
    protected <T> boolean extendAddOrUpdate(Boolean flag, T modelBean, boolean update, String key, Long userId) {
        return flag;
    }

    @Override
    public <T> Result addOrUpdate(T modelBean, boolean update) {
        SysUserTempModel userTempModel = (SysUserTempModel) modelBean;
        userTempModel.setParentId(Web.Util.getSessionUserId(request));
        if (!update) { // 添加
            QueryModel queryModel = getValidQueryModel();
            queryModel.addEq(SysUserTempModel::getParentId, Web.Util.getSessionUserId(request));
            long num = getCount(SysUserTempModel.class, queryModel);
            if (num >= 3) { // 此处暂时不做配置，防止逻辑混乱
                return Web.Response.error("临时账号超过限制个数！");
            }
        }
        Date dateUtile = userTempModel.getDateUntil();
        if (DateUtil.daysBetween(new Date(), dateUtile) > 30) { // 此处暂时不做配置，防止逻辑混乱
            return Web.Response.error("临时账号有效期超过限制天数！");
        }
        String operateName = "";
        if (update) { // 修改时记录
            SysUserTempModel userTempModelOld = getBaseDAO().findById(SysUserTempModel.class, userTempModel.getId());
            if (!userTempModelOld.getAccountName().equals(userTempModel.getAccountName())) {
                operateName += "账号名称:" + userTempModelOld.getAccountName() + ">" + userTempModel.getAccountName() + " ";
            }
            // 密码可能不传，先判断是否为null
            if (userTempModel.getPassword() != null && !userTempModelOld.getPassword().equals(userTempModel.getPassword())) {
                operateName += "修改密码:" + userTempModelOld.getPassword() + ">****** ";
            }
            if (!DateUtil.equals(userTempModelOld.getDateUntil(), userTempModel.getDateUntil())) {
                operateName += "有效期:" + DateUtil.getDateTimeString(userTempModelOld.getDateUntil()) + ">"
                        + DateUtil.getDateTimeString(userTempModel.getDateUntil()) + " ";
            }
            if ((userTempModelOld.getAllowIp() + "").trim().equals((userTempModelOld.getAllowIp() + "").trim())) {
                operateName += "允许登录的ip:" + userTempModelOld.getAllowIp() + ">" + userTempModel.getAllowIp() + " ";
            }
        }
        Result result = super.addOrUpdate(modelBean, update);
        if (result.getSuccess() && StringUtils.isNotBlank(operateName)) {
            SystemUser user = (SystemUser) Web.Util.getSessionUser(request);
            recordTempUserLog(user, userTempModel.getId(), TEMP_USER_LOG_UPDATE, operateName);
        }
        return result;
    }

}
